package com.javalearn.gulimail.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.javalearn.common.utils.HttpUtils;
import com.javalearn.common.utils.R;
import com.javalearn.gulimail.auth.feign.MemberFeignService;
import com.javalearn.common.vo.MemberResponseVo;
import com.javalearn.gulimail.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 处理社交登录请求
 */
@Controller
@Slf4j
public class Auth2Controller {
    @Autowired
    MemberFeignService memberFeignService;
    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession httpSession, HttpServletResponse httpServletResponse) throws Exception {
        //1,根据code换取accessToken
        Map<String,String> map = new HashMap<>();
        Map<String,String> header = new HashMap<>();
        Map<String,String> query = new HashMap<>();
        map.put("client_id","155205867");
        map.put("client_secret","24b052825b4aeaaa12f1648f2bea9d41");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.gulimail.com/oauth2.0/weibo/success");
        map.put("code",code);
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post",header,map,query);

        //处理响应
        if (response.getStatusLine().getStatusCode()==200){
            //获取到了accessToken
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json,SocialUser.class);

            //知道了当前是哪个社交用户
            //1.当前用户如果是第一次登录，那么就注册进来（为当前社交用户生成一个会员信息账号，以后这个社交账号就对应这个指定的会员）
            //登录或者注册这个社交用户（使用uid判断用户）
            R r = memberFeignService.oauthLogin(socialUser);
            if (r.getCode()==0){
                MemberResponseVo data = r.getData(new TypeReference<MemberResponseVo>(){});
                log.info("登录成功，用户信息:{}",data.toString());
                //第一次使用session，命令浏览器保存卡号,JESSIONID，以后浏览器访问那个网站，就会带着这个网站的cookie
                //gulimail.com有以下子域：auth.gulimail.com,order.gulimail.com
                //发卡的时候（指定为父域名），即使是子域系统发的卡，也能让父域使用
                //TODO 默认发的令牌，作用域任然是当前域，子域无法共享session
                //TODO 使用json的序列化方式来序列化对象数据到redis中
                httpSession.setAttribute("loginUser",data);
//                new Cookie("JESSIONID","dadaa").setDomain();
                return "redirect:http://gulimail.com";
            }else {
                return "redirect:http://auth.gulimail.com/login.html";
            }

        }else {
            return "redirect:http://auth.gulimail.com/login.html";
        }
    }
}
